/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.source.service.image;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.source.dao.image.EleSourceImageDao;
import com.thinkgem.jeesite.modules.source.dao.image.EleSourceImageGroupDao;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImage;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImageGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 图片资源管理Service
 * 
 * @author ZC
 * @version 2017-04-20
 */
@Service
@Transactional(readOnly = true)
public class EleSourceImageGroupService extends CrudService<EleSourceImageGroupDao, EleSourceImageGroup> {

	@Autowired
	private EleSourceImageDao eleSourceImageDao;

	public EleSourceImageGroup get(String id) {
		EleSourceImageGroup eleSourceImageGroup = super.get(id);
		eleSourceImageGroup.setEleSourceImageList(eleSourceImageDao.findList(new EleSourceImage(eleSourceImageGroup)));
		return eleSourceImageGroup;
	}

	public List<EleSourceImageGroup> findList(EleSourceImageGroup eleSourceImageGroup) {
		return super.findList(eleSourceImageGroup);
	}

	public Page<EleSourceImageGroup> findPage(Page<EleSourceImageGroup> page, EleSourceImageGroup eleSourceImageGroup) {
		return super.findPage(page, eleSourceImageGroup);
	}

	@Transactional(readOnly = false)
	public void save(EleSourceImageGroup eleSourceImageGroup) {
		System.out.println(eleSourceImageGroup);
		try {
			super.save(eleSourceImageGroup);
			for (EleSourceImage eleSourceImage : eleSourceImageGroup.getEleSourceImageList()) {
				System.out.println(eleSourceImage);

				if (eleSourceImage.getId() == null) {
					continue;
				}
				if (EleSourceImage.DEL_FLAG_NORMAL.equals(eleSourceImage.getDelFlag())) {
					if (StringUtils.isBlank(eleSourceImage.getId())) {
						eleSourceImage.setGroup(eleSourceImageGroup);
						eleSourceImage.preInsert();
						eleSourceImageDao.insert(eleSourceImage);
					} else {
						eleSourceImage.preUpdate();
						eleSourceImageDao.update(eleSourceImage);
					}
				} else {
					eleSourceImageDao.delete(eleSourceImage);
				}
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			logger.error("新建图片资源失败!");
		}
	}

	@Transactional(readOnly = false)
	public void delete(EleSourceImageGroup eleSourceImageGroup) {
		super.delete(eleSourceImageGroup);
		eleSourceImageDao.delete(new EleSourceImage(eleSourceImageGroup));
	}

}